﻿#include "LabelVerification.h"
#include <QPaintEvent>
#include <QPainter>
#include <QTime>

CLabelVerification::CLabelVerification(QWidget* parent /*= 0*/, Qt::WindowFlags flags)
	: QLabel(parent, flags)
{
	//生成随机种子
	qsrand(QTime::currentTime().second() * 1000 + QTime::currentTime().msec());
	m_colorArray = new QColor[m_letter_number];
	
	m_strVerificationCode.fill(QChar(), m_letter_number);
	m_noice_point_number = this->width();

}

CLabelVerification::~CLabelVerification()
{

}

QString CLabelVerification::getVerificationCode()
{
	return m_strVerificationCode.toUpper();
}

void CLabelVerification::init()
{

}

void CLabelVerification::mousePressEvent(QMouseEvent *event)
{
	repaint();
	QLabel::mousePressEvent(event);
}

void CLabelVerification::paintEvent(QPaintEvent * event)
{
	QPainter painter(this);
	QPoint p;
	//背景设为白色
	painter.fillRect(this->rect(), Qt::white);
	//产生4个不同的字符
	produceVerificationCode();
	//产生4个不同的颜色
	produceRandomColor();
	//绘制验证码
	for (int i = 0; i < m_letter_number; ++i)
	{
		p.setX(i * (this->width() / m_letter_number) + this->width() / 8 - 3);
		p.setY(this->height() / 2 + 6);
		painter.setFont(QFont(QStringLiteral("宋体"), 14));
		painter.setPen(m_colorArray[i]);
		painter.drawText(p, QString(m_strVerificationCode[i]));
	}
	//绘制噪点
	for (int j = 0; j < m_noice_point_number; ++j)
	{
		p.setX(qrand() % this->width());
		p.setY(qrand() % this->height());
		painter.setPen(m_colorArray[j % 4]);
		painter.drawPoint(p);
	}
	QLabel::paintEvent(event);
}

void CLabelVerification::produceVerificationCode()
{
	for (int i = 0; i < m_letter_number; ++i)
	{
		//m_strVerificationCode = m_strVerificationCode.replace(i, 1, QString(produceRandomLetter()));
		m_strVerificationCode.replace(i, 1, produceRandomLetter());
	}
}

QChar CLabelVerification::produceRandomLetter()
{
	QChar c;
	int flag = qrand() % m_letter_number;
	switch (flag)
	{
	case NUMBER_FLAG:
		c = '0' + qrand() % 10; break;
	case UPLETTER_FLAG:
		c = 'A' + qrand() % 26; break;
	case LOWLETTER_FLAG:
		c = 'a' + qrand() % 26; break;
	default:
		c = qrand() % 2 ? 'W' : 'D';
	}
	return c;
}

void CLabelVerification::produceRandomColor()
{
	for (int i = 0; i < m_letter_number; ++i)
	{
		m_colorArray[i] = QColor(qrand() % 255, qrand() % 255, qrand() % 255);
	}
}

